package com.agree.service;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.agree.common.AfaConfiguration;
import com.agree.common.AfaUtils;
import com.agree.common.ReturnResult;
import com.agree.consts.TransServiceCode;
import com.agree.utils.MD5Utils;
import com.agree.utils.SSLException;
import com.agree.utils.SSLUtils;
import com.alibaba.fastjson.JSONObject;

@Service
@Transactional
public class CommonService {
	
	@Autowired
	private AfaConfiguration afaConfiguration;
	
	private final Logger log = LoggerFactory.getLogger(CommonService.class);
	
	private final String TRAN_CODE = "tranCode";//交易码参数名
	
	private final String PASSWORD = "passwd";//密码参数名
	
	private final String IS_TOKEN = "isToken";//是否要求签名串参数名
	
	private final String ID = "_id";//签名时标记客户或电子账户的唯一标识参数名（可以是身份id可以是电子账号）
	
	private final String ID_NAME = "name";//若要签名时，请求参数关于唯一标识的参数格式是id:{name:"",value:""},name是签名时唯一标识参数名
	
	private final String ID_VALUE = "value";//若要签名时，请求参数关于唯一标识的参数格式是id:{name:"",value:""},value是签名时唯一标识参数值
	
	private final String TRAN_TIME = "trantime";//交易时间戳输入接口参数名
	
	private final String TOKEN_TIME = "tokentime";//签名串输入接口参数名

	public ReturnResult updateCommonPostRequest(Map<String, String> map) {
		ReturnResult res = new ReturnResult();
		//遍历参数
		if(map.isEmpty()) {
			res.setErrorLocation(1);
			res.setSuccess(false);
			res.setErrorMsg(afaConfiguration.getSysError());
			log.error("AFA访问失败：请求参数为空");
			return res;
		}
		String tranCode = TransServiceCode.transCodeDecode(map.get(TRAN_CODE));
		//解密
		//去除，该参数不参与传递
		map.remove(TRAN_CODE);
		String password = map.get(PASSWORD);
		if(password != null) {
			password = MD5Utils.string2MD5(password);
			map.replace(PASSWORD, password);
		}
		Boolean isToken = Boolean.valueOf(map.get(IS_TOKEN));
		if(isToken!=null && isToken) {
			String id = map.get(ID);
			//要签名的唯一电子账户确定值
			JSONObject jsonObject = null;
			if(id != null) {
				try {
					jsonObject = JSONObject.parseObject(id);
				} catch (Exception e) {
					res.setErrorLocation(1);
					res.setSuccess(false);
					res.setErrorMsg(afaConfiguration.getSysError());
					log.error("AFA访问失败：请求参数id不是json格式!");
					return res;
				}
			}
			//校验支付密码是否为空
			if(password==null) {
				password = "";
				map.put(PASSWORD, password);
			}
			String idName = jsonObject.getString(ID_NAME);
			String idValue = jsonObject.getString(ID_VALUE);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String tokenTime = sdf.format(new Date());
			String encryptMsg = toGetToken(password, idValue, tokenTime);
			map.put(TOKEN_TIME, encryptMsg);
			map.put(idName, idValue);
			map.put(TRAN_TIME, tokenTime);
			//去除多余的值
			map.remove(ID);
			map.remove(IS_TOKEN);
		}
		String bodyString = JSONObject.toJSONString(map);
		System.out.println(bodyString+"========================");
		//发请求获取结果
		try {
			AfaUtils.access(tranCode, bodyString, null, res);
			if(res.isSuccess()) {
				Object result = res.getResult();
				log.info(String.valueOf(result));
			}
		}catch (Exception e) {
			res.setErrorLocation(1);
			res.setSuccess(false);
			res.setErrorMsg(afaConfiguration.getSysError());
			log.error("AFA访问失败：" + e);
		}
		if (log.isInfoEnabled()) {
			log.info("AWEB返回JSON: \r\n" + JSONObject.toJSONString(res));
		}
		return res;
	}
	/**
	 * 获取签名串,前台传参需要例子:{custno:"",_id:{name:"medno",value:""},passwd:"",updown_reason:"",isToken:true}
	 * @param key
	 * @param value
	 * @param tokenTime2 
	 * @return
	 */
	private String toGetToken(String password, String id, String tokenTime) {
		try {
			 String encryptMsg = SSLUtils.encryptMsg(tokenTime, password, id);
			 return encryptMsg;
		} catch (InvalidKeyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SSLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}
	
	public ReturnResult updateCommonRequest(Map<String, String> map) {
		ReturnResult res = new ReturnResult();
		//遍历参数
		if(map.isEmpty()) {
			res.setErrorLocation(1);
			res.setSuccess(false);
			res.setErrorMsg(afaConfiguration.getSysError());
			log.error("AFA访问失败：请求参数为空");
			return res;
		}
		
		String tranCode = TransServiceCode.transCodeDecode(map.get(TRAN_CODE));
		map.remove(TRAN_CODE);
		String bodyString = JSONObject.toJSONString(map);
		System.out.println(bodyString+"========================");
		//发请求获取结果
		try {
			AfaUtils.access(tranCode, bodyString, null, res);
			if(res.isSuccess()) {
				Object result = res.getResult();
				log.info(String.valueOf(result));
			}
		}catch (Exception e) {
			res.setErrorLocation(1);
			res.setSuccess(false);
			res.setErrorMsg(afaConfiguration.getSysError());
			log.error("AFA访问失败：" + e);
		}
		if (log.isInfoEnabled()) {
			log.info("AWEB返回JSON: \r\n" + JSONObject.toJSONString(res));
		}
		return res;
	}

}
